package cn.doubly.Service;

import cn.doubly.Bean.Message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/chat/{username}")
public class ChatService {

    //用一个线程安全的map保存在线的session
    public static Map<Session,String> onlineSessions = new ConcurrentHashMap<>();
    private static Logger log = LoggerFactory.getLogger(ChatService.class);

    //1.客户端打开连接
    @OnOpen
    public void onOpen(Session session,@PathParam(value = "username") String username){
        log.info(username + " 与服务器建立连接");
        onlineSessions.put(session,username);
        sendToAll(Message.jsonStr(Message.ENTER,"",username,"",onlineSessions.size()));
    }

    //2.客户端发送消息
    @OnMessage
    public void onMessage(Session session,String jsonStr){
        log.info(onlineSessions.get(session) + " 发送消息");
        log.info(jsonStr);
        Message message = JSON.parseObject(jsonStr,Message.class);
        if("".equals(message.getToUser()) || message.getToUser() == null){
            //发送给所有
            sendToAll(Message.jsonStr(Message.SPEAK,message.getMsg(),message.getFromUser(),message.getToUser(),onlineSessions.size()));
        }else{
            //发送给指定
        }
    }

    //3.客户端关闭连接
    @OnClose
    public void onClose(Session session){
        log.info(onlineSessions.get(session) + " 连接关闭");
        String str = Message.jsonStr(Message.QUIT,"",onlineSessions.get(session),"",onlineSessions.size());
        onlineSessions.remove(session);
        sendToAll(str);
    }

    //4.发生异常
    @OnError
    public void onError(Session session,Throwable error){
        log.error(onlineSessions.get(session)+"发生异常");
        log.error(error.getMessage());
    }

    //发送消息给所有人
    private static void sendToAll(String jsonMsg){
        onlineSessions.forEach((session,username) -> {
            try {
                session.getBasicRemote().sendText(jsonMsg);
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        });
    }

}
